from socket import *
from thread import *
import time
from random import randint
import sys

basesocket = socket(AF_INET,SOCK_STREAM)
basesocket.bind(("127.0.0.1",3724))
basesocket.listen(4)
gameip = ""


class Tools:
	def __init__(self):
		None
	def str2int(self,string):
		temp = ""
		tstring = ""
		for x in range(len(string)):
			tstring += string[len(string)-1-x]
		for x in tstring:
			ttemp = hex(ord(x))
			temp += ttemp[len(ttemp)-2:len(ttemp)]
		ret = 0
		exec("ret = 0x%s"%temp)
		return ret

	def sleep(self,sec):
		print "Sleeping"
		tim = time.time()
		while time.time() - tim < sec:
			None
		print "Done"
	def replace(self,string,old,new):
		for x in range(len(string)):
			if string[x] == old[0] and x+len(old) <= len(string):
				return string[0:x] + new + string[x+len(old):len(string)]
		return string

	def lenght2revchar(self,string):
		lenght = len(string)-3
		hexs = hex(lenght)
		h1 = hexs[2:4]
		h2 = hexs[4:6]
		exec("h1 = 0x%s"%h1)
		exec("h2 = 0x%s"%h2)
		hexs = chr(h2)+chr(h1)
		return hexs

	def getend(self,string,instring):
		for x in range(len(string)):
			if string[x] == instring[0] and x+len(instring) <= len(string):
				if string[x:x+len(instring)] == instring:
					return x+len(instring)


	def findfrom(self,string,char,wfrom):
		newstr = string[wfrom:len(string)]
		for x in range(len(newstr)):
			if newstr[x] == char:
				return wfrom+x

	def isin(self,string,instring):
		for x in range(len(string)):
			if string[x] == instring[0] and x+len(instring) <= len(string):
				if string[x:x+len(instring)] == instring:
					return 1
		return 0
	def getbetween(self,string,first,last):
		end = -1
		start = -1
		for x in range(len(string)):
			if string[x] == first[0] and x+len(first) <= len(string):
				if string[x:x+len(first)] == first:
					None

	def ServerListCheck(self,data,ssock,gameserver):
		#if ord(data[0]) == 16:
		#	print data
		#	global gameip
		#	srvlst = ""
		#	lenght = self.str2int(data[1:3])
		#	lenght+=3
		#	srvlst += data
		#	while len(srvlst) < lenght:
		#		data = ssock.recv(1024)
		#		srvlst += data
		#	endsrv = self.getend(srvlst.lower(),gameserver.lower())
		#	ffrom = self.findfrom(srvlst,":",endsrv)
		#	gameip = srvlst[endsrv+1:ffrom]
		#	print gameip
		#	salst = ""
		#	for x in range(len(srvlst)):
		#		if x == endsrv-1:
		#			salst+="s"
		#		else:
		#			salst+=srvlst[x]
		#	srvlst[endsrv-1]
		#	data = srvlst[0:endsrv+1]+"127.0.0.1:3724"+srvlst[ffrom+5:len(srvlst)]
		#	data = data[0] + self.lenght2revchar(data) + data[3:len(data)]
		#	#srvlst = self.vervang(srvlst,"S","P")
		#	return data
		if ord(data[0]) == 16:
			global gameip
			srvlst = ""
			lenght = self.str2int(data[1:3])
			lenght+=3
			srvlst += data
			while len(srvlst) < lenght:
				data = ssock.recv(1024)
				srvlst += data
			endsrv = self.getend(srvlst.lower(),gameserver.lower())
			ffrom = self.findfrom(srvlst,":",endsrv)
			gameip = srvlst[endsrv+1:ffrom]
			data = srvlst[0:endsrv+1] + "127.0.0.1:3724" + srvlst[ffrom+5:len(srvlst)]
			data = data[0] + self.lenght2revchar(data) + data[3:len(data)]
			a = open("slkd.txt","wb")
			a.write(data)
			a.close()
			return data			
		else:
			return data

class World(Tools):
	def __init__(self,sock,worldserver,gameserver,port=3724):
		self.csock = sock
		self.worldserver = worldserver
		self.port = port
		self.ssock = ""
		self.connect = 0
		self.gameserver = gameserver
	def server(self):
		print "World Server Forwarding started"
		self.ssock = socket(AF_INET,SOCK_STREAM)
		self.ssock.connect((self.worldserver,self.port))
		self.connect = 1
		while 1:
			data = self.ssock.recv(1024)
			if not data == "":
				data = self.ServerListCheck(data,self.ssock,self.gameserver)
				a = open("test.mf","ab")
				a.write(data)
				a.close()
				self.csock.send(data)
	def client(self):
		try:
			print "World Client Forwarding started"
			while self.connect == 0:
				None
			while 1:
					data = self.csock.recv(1024)
					if not data == "":	
							self.ssock.send(data)
		except:
			print "Sorry:", sys.exc_type, ":", sys.exc_value

class Game(Tools):
	def __init__(self,sock,gameserver,port=3724):
		self.csock = sock
		self.port = port
		self.ssock = ""
		self.connect = 0
		self.gameserver = gameserver
		self.packetloss = 0
	def server(self):
		print "Game Server Forwarding started"
		self.ssock = socket(AF_INET,SOCK_STREAM)
		print "Connecting to %s:%s"%(self.gameserver,self.port)
		self.ssock.connect((self.gameserver,self.port))
		self.connect = 1
		num = 0
		while 1:
			data = self.ssock.recv(1024)
			if not data == "":
				if len(data) >= 6:
					if ord(data[5]) == 0x07:
						print "Someone said: %s"%data[33:len(data)-2]
				#data = self.ServerListCheck(data,self.ssock,self.gameserver)
				self.csock.send(data)
			num += 1
	def client(self):
		print "Game Client Forwarding started"
		while self.connect == 1:
			None
		num = 0
		while 1:
			data = self.csock.recv(1024)
			if not data == "":
					if len(data) >= 11:
						if ord(data[10]) == 0x07:
							print "You said: %s"%data[14:len(data)-1]
					self.ssock.send(data) #353 356
			num+=1

	def cmdline(self):
		while 1:
			data = raw_input(">>> ")
			if data == "pl":
				self.packetloss = 1
			if data == "npl":
				self.packetloss = 0
			
			

time = 0
while 1:
		print "Waiting for connections"
		sock,addr = basesocket.accept()
		print "Connection from",addr
		if time == 0:
			world = World(sock,"eu.logon.worldofwarcraft.com", "Stormreaver")
			start_new_thread(world.client,())
			start_new_thread(world.server,())
		if time == 1:
			print gameip,"IP"
			game = Game(sock,gameip)
			start_new_thread(game.client,())
			start_new_thread(game.server,())
			start_new_thread(game.cmdline,())
		time += 1


	# 141 - 261
	# 158 - 311
	# 159 - 313
